package com.bw.module_login.view

import android.util.Log
import androidx.activity.viewModels
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.login.vm.LoginViewModel
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.bw.lib_base.path.RouterPath
import com.bw.lib_common.entity.UserEntity
import com.bw.lib_common.view.BaseMvvmActivity
import com.bw.module_login.R
import com.bw.module_login.databinding.ActivityLoginBinding

@Route(path =RouterPath.PATH_LOGIN_PAGE)
class LoginActivity : BaseMvvmActivity<ActivityLoginBinding>() {

    private val vm: LoginViewModel by viewModels()

    override fun initViews() {
        super.initViews()

        val password=intent.getStringExtra("password")
        val username=intent.getStringExtra("username")

        if (!password.isNullOrEmpty() && !username.isNullOrEmpty()){
            mDataBinding.includeLoginLayout.edtUserName.setText(username)
            mDataBinding.includeLoginLayout.edtPassWold.setText(password)
        }

        //登录
        mDataBinding.includeLoginLayout.tvLoginBtn.setOnClickListener {
            val userName = mDataBinding.includeLoginLayout.edtUserName.text.toString()
            val userPwd = mDataBinding.includeLoginLayout.edtPassWold.text.toString()
            //发起网络请求
            vm.loginToServer(userPwd, userName)
        }

        //跳转到注册
        mDataBinding.includeLoginLayout.tvRegisterNew.setOnClickListener {
            ARouter.getInstance().build(RouterPath.PATH_REGISTER_PAGE).navigation()
        }
    }

    override fun loadData(){

        vm.mErrorLiveData.observe(this@LoginActivity){
            showToast(it)
            Log.i("sss", "loadData: ${it}")
        }

        vm.mSuccessLiveData.observe(this@LoginActivity){
            if(it != null){
                SPUtils.getInstance().put("username",(it as UserEntity).username)
                showToast("登录成功")
                //跳转到主页面
                ARouter.getInstance().build(RouterPath.PATH_MAIN_PAGE).navigation()
            }
        }
    }


    override fun observeDataChange() {}

    override fun getLayoutId(): Int = R.layout.activity_login

}